<?php

namespace console\models;

use Yii;
use common\helpers\ArrayHelper;
use yii\base\Exception;

/**
 * This is the model class for table "user".
 *
 * @property integer $id
 * @property string $username
 * @property string $avatar
 * @property string $email
 * @property string $realname
 * @property string $auth_key
 * @property string $password_hash
 * @property string $password_reset_token
 * @property integer $status
 * @property integer $created_at
 * @property integer $updated_at
 */
class FrontUser extends \common\base\Model {

    /**
     * @var array 客队信息
     */
    public $tablename = '{{%user_meta}}';

    /**
     * @var integer 比赛ID
     */
    public $username;

    /**
     * @var integer 比赛状态
     */
    public $email;

    /**
     * @var integer 比赛时间
     */
    public $mobile;

    /**
     * @var array 赛季信息
     */
    public $password = '123456';

    /**
     * @var array 主队信息
     */
    public $signature = '';

    /**
     * @var array 客队信息
     */
    public $location = '';

    /**
     * @var array 客队信息
     */
    public $qq;

    /**
     * @var array 客队信息
     */
    public $empno;

    /**
     * @var array 主队信息
     */
    private $_gender;

    /**
     * @var array 赛事信息集合
     */
    private $_avatar;

    /**
     * @var integer 当前比赛主队ID
     */
    private $_cover;

    /**
     * @var array 客队信息
     */
    private $_birthday;

    /**
     * @var array 客队信息
     */
    private $_ip;

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['username'], 'required'],
            [['username', 'mobile'], 'string', 'max' => 32],
            [['email'], 'string', 'max' => 60],
            [['location', 'signature', 'password', 'signature', 'qq', 'empno'], 'string'],
        ];
    }

    /**
     * 数据加密
     * @param string $data
     */
    protected function encryptData($data, $encrypt = false) {
        if (!$data) {
            return $data;
        }
        /* @var $security \common\base\Security */
        $security = Yii::$app->security;
        if ($encrypt) {
            return $security->encryptMaster($data);
        }
        return $security->generatePrivateKey($data);
    }

    public function setAvatar($avatar) {
        $this->_avatar = $avatar;
    }

    public function getAvatar() {
        return $this->_avatar ?: '/attachments/avatar/' . date('Ym/d/') . md5(uniqid(time())) . '.png';
    }

    public function setCover($cover) {
        $this->_cover = $cover;
    }

    public function getCover() {
        return $this->_cover ?: '/attachments/cover/' . date('Ym/d/') . md5(uniqid(time())) . '.png';
    }

    public function setGender($gender) {
        $this->_gender = $gender;
    }

    public function getGender() {
        return $this->_gender ?: rand(0, 2);
    }

    public function setBirthday($birthday) {
        $this->_birthday = $birthday;
    }

    public function getBirthday() {
        return $this->_birthday ?: date('Y-m-d', rand(0, 978192000));
    }

    public function setIp($ip) {
        $this->_ip = $ip;
    }

    public function getIp() {
        return $this->_ip ?: rand(0, 999999999);
    }

    public function getUserData() {
        return [
            'nickname' => $this->username,
            'mobile' => $this->encryptData($this->mobile, true),
            'avatar' => $this->avatar,
            'cover' => $this->cover,
            'gender' => $this->gender,
            'signature' => $this->signature,
            'birthday' => $this->birthday,
            'location' => $this->location,
            'ip' => $this->ip,
            'qq' => rand(10000001, 13999999999),
            'empno' => rand(100000, 999999),
        ];
    }

    public function save() {
        $user = new User();
        $connection = Yii::$app->db;
        $transaction = $connection->beginTransaction();
        $command = $connection->createCommand();
        try {
            $user->setMobile($this->mobile);
            $user->setPassword($this->password);
            $user->generateAuthKey();
            $user->username = $this->username;
            $user->email = $this->email;
            if (!$user->save()) {
                throw new Exception($user->getErrorMsg());
            }
            $metaData = ArrayHelper::merge($this->getUserData(), [
                'id' => $user->id,
                'created_at' => $user->created_at,
                'updated_at' => $user->updated_at,
            ]);
            $meta = $command->insert($this->tablename, $metaData)->execute();
            if (!$meta) {
                throw new Exception('用户插入失败');
            }
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            return $e->getMessage();
        }
        return true;
    }

}
